package com.aaa.sys.controller;


import com.aaa.vo.R;
import com.aaa.sys.entity.Dept;
import com.aaa.sys.entity.Role;
import com.aaa.sys.service.RoleService;
import com.aaa.sys.vo.RoleExcel;
import com.aaa.sys.vo.RoleSearch;
import com.aaa.util.ExcelUtil;
import com.aaa.util.JwtUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author ykq
 * @since 2020-11-25
 */
@RestController
@RequestMapping("/system/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    //导出excel
    @PostMapping("/exportRole")
    public void exportData(HttpServletResponse response,@RequestBody List<Role> roles) {
        String fileName = "角色列表";
        String sheetName = "角色列表";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<RoleExcel> userExcelList = new ArrayList<>();
        for (Role role : roles) {
            RoleExcel roleExcel = new RoleExcel();
            BeanUtils.copyProperties(role,roleExcel);
            userExcelList.add(roleExcel);
        }
        try {
            ExcelUtil.writeExcel(response, userExcelList, fileName, sheetName, RoleExcel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/download")
    public void download(HttpServletResponse response,@RequestBody List<Role> roles) throws IOException {
        //文件名需要这样写，不能在setHeader直接写中文名，否则下载的文件名字为空，只有后缀
        String fileName = new String("角色管理.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName );
        List<RoleExcel> userExcelList = new ArrayList<>();
        for (Role role : roles) {
            RoleExcel roleExcel = new RoleExcel();
            BeanUtils.copyProperties(role,roleExcel);
            userExcelList.add(roleExcel);
        }
        EasyExcel.write(response.getOutputStream(), Role.class)
                .sheet("sheet")
                .doWrite(userExcelList);
    }


    @PostMapping("searchRole/{page}/{limit}")
    public R searchRole(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody RoleSearch roleSearch){
        Page<Role> deptPage = this.roleService.searchRole(page, limit, roleSearch);
        return R.ok().data("records",deptPage.getRecords()).data("total",deptPage.getTotal());
    }

    @PostMapping("addRole")
    public R addRole(@RequestBody Role role, HttpServletRequest request){
        try {
            role.setCreateTime(new Date());
            role.setUpdateUser(JwtUtils.getMemberIdByJwtToken(request.getHeader("token")));
            boolean save = this.roleService.save(role);
            return R.ok().message("添加角色成功");
        }catch (Exception e){
            return R.error().message("添加角色失败");
        }
    }

    @PostMapping("updateRole")
    public R updateRole(@RequestBody Role role){
        try {
            boolean save = this.roleService.updateById(role);
            return R.ok().message("修改角色成功");
        }catch (Exception e){
            return R.error().message("修改角色失败");
        }
    }

    @GetMapping("findById/{roleId}")
    public R findById(@PathVariable Long roleId){
        Role role = this.roleService.getById(roleId);
        return R.ok().data("role",role);
    }

    @DeleteMapping("deleteRole/{roleId}")
    public R deleteRole(@PathVariable Long roleId){
        try {
            boolean save = this.roleService.removeRoleById(roleId);
            return R.ok().message("修改角色成功");
        }catch (Exception e){
            return R.error().message("修改角色失败");
        }
    }

    @PostMapping("addRolePermission/{roleId}")
    public R addRolePermission(@PathVariable Long roleId,  @RequestBody List<Long> menuIds){
            try {
                this.roleService.saveRolePermission(roleId,menuIds);
                return R.ok().message("角色分配权限成功");
            }catch (Exception e){
                e.printStackTrace();
                return R.error().message("角色分配权限失败");
            }
    }

    @GetMapping("findAll/{userId}")
    public R findAll(@PathVariable("userId")Long userId){
        List<Role> list = this.roleService.list();
        List<Long> userRoles = this.roleService.queryRoleIdsByUserId(userId);
        return  R.ok().data("roles",list).data("userRoles",userRoles);
    }

}

